import express from 'express'

import { getFileNamesBySuffix } from '../utils/io'
import { staticPath } from '../utils/path'
import getValidIPAddress from '../utils/networkAddress'
import { success, info } from '../utils/output'

const invalidPageMsg = `<h3>404 Not Found<a href="/"><br>Back Home</a></h3>`

const createServer = async (): Promise<void> => {
  // 获取本机 IPv4 地址和可用的端口
  const { IPAddress, port } = await getValidIPAddress()
  // 读取文件夹下的文件
  const htmlFiles: Array<string> = await getFileNamesBySuffix(staticPath, 'html')
  const urls = htmlFiles.reduce((prev, curr) => prev + `<a href="/static/${curr}.html">${curr}</a><br>`, 'Results: <br>')
  const app = express()
  info('启动服务器...')
  app
    .use('/static', express.static(staticPath))
    .get('/', (_, res) => {
      res.status(200).send(urls)
    })
    .use((_, res) => {
      res.status(404).setHeader('Content-Type', 'text/html').send(invalidPageMsg)
    })
    .listen(port, () => {
      // 监听端口 生成二维码
      success('服务已启动')
      info(`本机地址  : http://localhost:${port}`)
      info(`局域网地址: http://${IPAddress}`)
    })
}

export default createServer
